//
//  JPMainTabBarItem.swift
//  JPWeibo
//
//  Created by 哇咔咔 on 16/9/19.
//  Copyright © 2016年 jp. All rights reserved.
//

import UIKit

protocol JPMainTabBarDelegate: NSObjectProtocol {
    
    func didSelectedComposeButton()
}

class JPMainTabBar: UITabBar {
    
    var composeButtonClosure: (() -> ())?
    
    weak var composeDelegate: JPMainTabBarDelegate?
    
    lazy var composeButton: UIButton! = {
        
        let composeButton = UIButton()
        composeButton.setImage(UIImage(named: "tabbar_compose_icon_add"), for: .normal)
        composeButton.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), for: .highlighted)
        
        composeButton.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: .normal)
        composeButton.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted  "), for: .highlighted)
        
        composeButton.sizeToFit()
        
        composeButton.addTarget(self, action: #selector(composeClickAction), for: .touchUpInside)
        return composeButton
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.setupUI()
    }
    
    private func setupUI() {
        
        addSubview(composeButton)
        backgroundImage = UIImage(named: "tabbar_background")
    }
    
    @objc private func composeClickAction() {
        
        composeButtonClosure?()
        composeDelegate?.didSelectedComposeButton()
    }
    
    //在这里重新布局子控件
    override func layoutSubviews() {
        super.layoutSubviews()
        
        composeButton.centerX = width / 2
        composeButton.centerY = height / 2
        
        let barButtonWidth = width / 5
        var index = 0
        
        for value in subviews {
            
            if value.isKind(of: NSClassFromString("UITabBarButton")!) {
                
                value.x = CGFloat(index) * barButtonWidth
                index += 1

                if index == 2 {
    
                    index += 1
                }
            }
        }
    }
}
